<template>
  <div
    v-loading="loadingSave"
    class="app-container"
    style="height: 100%"
    element-loading-text="加载中..."
  >
    <div style="padding-bottom: 12px" class="">
      <div class="header flex-justify-between">
        <span class="title_tip">{{ route.params.id ? '编辑商家' : '新建商家' }}</span>
        <div class="footer_btn_save">
          <el-button
            color="#007cff"
            style="width: 3.2vw"
            @focus="btnCancelFocus"
            @click="addSave(formRef)"
            >保存</el-button
          >
          <el-button style="width: 3.2vw" @click="onBack(formRef)"> 取消 </el-button>
        </div>
      </div>
    </div>
    <div class="app-container-inner" style="display: flex; flex-direction: column; flex: 1">
      <!-- 创建网点 -->
      <div class="create-work">
        <el-form
          ref="formRef"
          label-width="auto"
          label-position="right"
          :model="data"
          require-asterisk-position="left"
          :rules="rules"
        >
          <h3 class="title">商家信息</h3>
          <section class="basic_information">
            <ul class="left_info">
              <li>
                <el-form-item label="商家名称" prop="name">
                  <el-input v-model.trim="data.name" placeholder="请输入商家名称" clearable />
                </el-form-item>

                <!-- 绑定账号 -->
                <el-form-item label="绑定账号" prop="accountPhone">
                  <span class="flex_item">
                    <el-input
                      v-model.trim="data.accountPhone"
                      maxlength="11"
                      clearable
                      placeholder="请输入绑定的手机号"
                    />
                    <el-button
                      type="primary"
                      class="ma_left"
                      color="#007cff"
                      round
                      size="small"
                      @focus="btnCancelFocus"
                      @click="empPageSelecctList(data.accountPhone)"
                      >获取</el-button
                    >
                  </span>
                </el-form-item>

                <!-- 负责人员 -->
                <el-form-item label="负责人员" prop="accountName">
                  <span class="flex_item">
                    <el-input
                      v-model.trim="data.accountName"
                      :disabled="isInput"
                      clearable
                      placeholder="根据绑定手机号获取"
                    />
                    <el-tooltip effect="light" content="获取不到则手动输入！" placement="right">
                      <el-icon size="18" class="ma_left" color="#ff5733">
                        <Warning />
                      </el-icon>
                    </el-tooltip>
                  </span>
                </el-form-item>
                <el-form-item label="工单策略">
                  <el-button
                    type="primary"
                    color="#007cff"
                    size="small"
                    round
                    @click="oredrDialog = true"
                  >
                    前往编辑策略
                    <el-icon class="icon_right" color="#007cff" size="14">
                      <Right />
                    </el-icon>
                  </el-button>
                </el-form-item>
                <el-form-item label="商家状态">
                  <el-radio-group v-model="data.status">
                    <el-radio :value="2">启用</el-radio>
                    <el-radio :value="4">禁用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </li>
              <li>
                <el-form-item label="联系人" prop="username">
                  <el-input v-model.trim="data.username" placeholder="请输入联系人" clearable />
                </el-form-item>
                <el-form-item label="联系人电话" prop="phone">
                  <el-input
                    v-model.trim="data.phone"
                    maxlength="11"
                    clearable
                    placeholder="联系人电话"
                /></el-form-item>
                <el-form-item required label="网点地址" prop="province">
                  <SingleAddress
                    ref="addrsDom"
                    :address="addrs"
                    class="addrsDom_"
                    @value-change="addressValChange"
                  />
                </el-form-item>
                <el-form-item label="详细地址" prop="address">
                  <el-input
                    v-model.trim="data.address"
                    :autosize="{ minRows: 1, maxRows: 4 }"
                    type="textarea"
                    maxlength="200"
                    show-word-limit
                    placeholder="请输入详细地址"
                    clearable
                  />
                </el-form-item>
              </li>
            </ul>
          </section>
          <h3 class="title">商家结算</h3>
          <el-button plain color="#007cff" class="add_btn" size="small" @click="onAddItem"
            >新增</el-button
          >
          <section class="table_list">
            <el-table
              height="100%"
              style="position: absolute"
              :data="data.moduleSettlements"
              :border="true"
              stripe
              resizable
            >
              <template #empty>
                <el-empty description="暂无数据" :image-size="140" />
              </template>
              <el-table-column label="序号" width="70" fixed>
                <template #default="scope">
                  <span class="order"> {{ scope.$index + 1 }} </span>
                  <span class="add_delete">
                    <el-icon size="16" color="#007cff" class="add" @click="onAddItem()">
                      <CirclePlus />
                    </el-icon>
                    <el-icon
                      color="rgba(245, 108, 108, 1)"
                      size="16"
                      @click="detelePri(scope.row, scope.$index)"
                    >
                      <Delete />
                    </el-icon>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                label="工单类型"
                prop="name"
                min-width="200"
                align="center"
              >
                <template #default="i">
                  <el-select
                    v-model="i.row.moduleId"
                    placeholder="请选择模块"
                    filterable
                    clearable
                    :remote-method="(val) => inputWorkModChange(val, i.$index)"
                    :loading="loading"
                    remote
                    remote-show-suffix
                  >
                    <el-option
                      v-for="item in i.row.workModulePrice"
                      :disabled="isStop(item.id)"
                      :value="item.id"
                      :label="item.name"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                label="模块默认费用"
                min-width="120"
                align="center"
              >
                <template #default="item">
                  <el-input
                    :value="
                      item.row.moduleId
                        ? item.row.workModulePrice?.filter((o) => item.row.moduleId == o.id)[0]
                            ?.price
                        : ''
                    "
                    disabled
                  >
                    <template #prepend>￥</template></el-input
                  >
                </template>
              </el-table-column>
              <el-table-column show-overflow-tooltip label="结算模式" min-width="80" align="center">
                <template #default="item">
                  <el-switch
                    v-model="item.row.containSpare"
                    inline-prompt
                    active-text="包含物料"
                    inactive-text="不包含物料"
                  />
                </template>
                <template #header>
                  结算模式
                  <el-popover ref="popover" placement="top-start" trigger="click" :width="160">
                    <h5 style="margin-bottom: 10px">批量填充结算模式</h5>
                    <el-switch
                      v-model="AllType"
                      inline-prompt
                      active-text="包含物料"
                      inactive-text="不包含物料"
                    />
                    <div style="display: flex; justify-content: end; margin-top: 10px">
                      <el-button
                        color="#007cff"
                        style="padding: 0 4px; height: 20px"
                        @click="changeAllType"
                        >确定</el-button
                      >
                    </div>
                    <template #reference>
                      <span class="multiple_btn">批量</span>
                    </template>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column
                prop="qty"
                show-overflow-tooltip
                label="商家结算价"
                min-width="140"
                align="center"
              >
                <template #header>
                  商家结算价
                  <el-popover ref="popover2" placement="top-start" trigger="click" :width="160">
                    <h5 style="margin-bottom: 10px">批量填充数量</h5>
                    <el-input
                      v-model.trim="Allprice"
                      placeholder="请输入"
                      @input="Allprice = Allprice.replace(/[^0-9]/g, '')"
                      @keyup.enter="changeAllAllprice"
                    ></el-input>
                    <div style="display: flex; justify-content: end; margin-top: 10px">
                      <el-button
                        color="#007cff"
                        style="padding: 0 4px; height: 20px"
                        @click="changeAllAllprice"
                        >确定</el-button
                      >
                    </div>
                    <template #reference>
                      <span class="multiple_btn">批量</span>
                    </template>
                  </el-popover>
                </template>
                <template #default="item">
                  <el-input
                    v-model.trim="item.row.price"
                    placeholder="结算价"
                    :formatter="(value) => `${value}`.replace(/[^\d]/g, '')"
                    :parser="(value) => value.replace(/[^\d]/g, '')"
                  >
                    <template #prepend>￥</template></el-input
                  >
                </template>
              </el-table-column>
            </el-table>
          </section>
        </el-form>
      </div>
    </div>

    <!-- 修改商家策略弹窗 -->
    <el-dialog
      v-model="oredrDialog"
      title="商家策略"
      width="400px"
      :draggable="true"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      class="order-dialog"
      top="8vh"
    >
      <el-form label-width="80" :model="data.strategy">
        <!--查看物料-->
        <el-form-item label="查看物料">
          <el-switch v-model="data.strategy.enableSpareAuthori" />
        </el-form-item>
        <template v-if="data.strategy.enableSpareAuthori">
          <!--申请物料-->
          <el-form-item label="申请物料">
            <el-radio-group v-model="data.strategy.enableApplySpare">
              <el-radio :value="true">启用</el-radio>
              <el-radio :value="false">关闭</el-radio>
            </el-radio-group>
          </el-form-item>

          <!--审核物料-->
          <el-form-item label="审核物料">
            <el-radio-group v-model="data.strategy.enableCheckSpare">
              <el-radio :value="true">启用</el-radio>
              <el-radio :value="false">关闭</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <!--查看费用-->
        <el-form-item label="查看费用">
          <el-switch v-model="data.strategy.enableFeeAuthori" />
        </el-form-item>
        <template v-if="data.strategy.enableFeeAuthori">
          <!--申请费用-->
          <el-form-item label="申请费用">
            <el-radio-group v-model="data.strategy.enableApplyFee">
              <el-radio :value="true">启用</el-radio>
              <el-radio :value="false">关闭</el-radio>
            </el-radio-group>
          </el-form-item>

          <!--审核费用-->
          <el-form-item label="审核费用">
            <el-radio-group v-model="data.strategy.enableCheckFee">
              <el-radio :value="true">启用</el-radio>
              <el-radio :value="false">关闭</el-radio>
            </el-radio-group>
          </el-form-item>
        </template>

        <el-form-item label="余额不足">
          <el-radio-group v-model="data.strategy.orderBalanceStrategy">
            <el-radio :value="1">允许下单</el-radio>
            <el-radio :value="2">禁止下单</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div class="footer btns">
        <el-button color="#007cff" style="width: 3.2vw" @click="oredrDialog = false"
          >确定</el-button
        >
        <el-button style="width: 3.2vw" @click="oredrDialog = false"> 取消 </el-button>
      </div>
    </el-dialog>

    <!-- 修改质保标准弹窗 -->
    <el-dialog
      v-model="quaDialog"
      title="修改网点质保标准"
      width="500px"
      :draggable="true"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      class="qua-dialog"
      top="8vh"
    >
      <div class="cards">
        <div class="card">
          <label>服务类型</label>
          <el-input v-model.trim="input11" disabled class="input-w" />
        </div>
        <div class="card">
          <label>默认时间</label>
          <el-input v-model.trim="input12" disabled class="input-w" />
        </div>
        <div class="card">
          <label>网点时间</label>
          <el-input v-model.trim="input13" class="input-w" />
        </div>
        <p>质保时间修改后，只针对新工单有效，已完成工单和进展中工单不受影响</p>
      </div>
      <div class="btns">
        <el-button class="btn_cancel" @click="quaDialog = false"> 取消 </el-button>
        <el-button color="#007cff" class="btn_save">保存</el-button>
      </div>
    </el-dialog>

    <!-- 修改费用标准弹窗 -->
    <el-dialog
      v-model="costDialog"
      title="修改网点费用标准"
      width="500px"
      :draggable="true"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      class="qua-dialog"
      top="8vh"
    >
      <div class="cards">
        <div class="card">
          <label>费用类型</label>
          <el-input v-model.trim="input14" disabled class="input-w" />
        </div>
        <div class="card">
          <label>默认费用</label>
          <el-input v-model.trim="input15" disabled class="input-w" />
        </div>
        <div class="card">
          <label>网点费用</label>
          <el-input v-model.trim="input16" class="input-w" />
        </div>
        <p>费用标准修改后，只针对未审核费用有效，已审核和已结算费用不受影响</p>
      </div>
      <div class="btns">
        <el-button class="btn_cancel" @click="costDialog = false"> 取消 </el-button>
        <el-button color="#007cff" class="btn_save">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import SingleAddress from '../../../components/address/singleAddress.vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ref, reactive, onMounted, watch } from 'vue'
  import { getBeforeUpdateSelect, factorySave } from '../../../api/merchant'
  import { getInfoAccount } from '../../../api/organize'
  import { workModulePricePageSelect } from '../../../api/order'
  import { ElMessage } from 'element-plus'
  import { phone, verifyPhone, setProvince } from '../../../utils/validate'
  import { useSettingStore } from '../../../store/modules/setting'
  import { useTagsViewStore } from '../../../store/modules/tagsView'
  import * as _ from 'lodash'
  import { CirclePlus, Delete, Right, Warning } from '@element-plus/icons-vue'

  // 修改质保标准
  const input11 = ref('安装') // 服务类型
  const input12 = ref(60) // 默认时间
  const input13 = ref('') // 网点时间
  // 修改费用标准
  const input14 = ref('测试') // 费用类型
  const input15 = ref(666) // 默认费用
  const input16 = ref('') // 网点费用
  const quaDialog = ref(false)
  const costDialog = ref(false)
  const SettingStore = useSettingStore()
  // 刷新页面
  const refresh = () => {
    SettingStore.setReload()
  }
  const TagsViewStore = useTagsViewStore()
  const popover = ref()
  const popover2 = ref()
  const addrsDom = ref()
  const formRef = ref()
  const router = useRouter()
  const route = useRoute()
  const loadingSave = ref(false)
  let loading = ref(false)
  let oredrDialog = ref(false)
  const isInput = ref(true)
  let addrs = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })
  let data: any = ref({
    accountId: null, //品牌商家账号ID
    phone: '', //	联系人电话
    accountName: '', //网点负责人名称
    accountPhone: '', //	绑定账号(手机号)
    address: '',
    area: '',
    province: '',
    city: '',
    town: '',
    username: '', //	联系人名称
    delModuleSettlementIds: [], //删除的服务模块结算对象ID
    id: null, //商家ID，新增不必传，修改必传
    moduleSettlements: [], //服务模块结算对象
    name: '', //商家名称
    status: 2, //	商家状态：false-启用，true-禁用
    strategy: {
      //品牌商家策略对象
      enableApplyFee: false, //是否开启申请工单费用：false-不开启，true-开启，当enableFeeAuthori=true时生效
      enableApplySpare: false, //是否开启申请工单物料：false-不开启，true-开启，当enableSpareAuthori=true时生效
      enableCheckFee: false, //	是否开启审核工单费用：false-不开启，true-开启，当enableFeeAuthori=true时生效
      enableCheckSpare: false, //是否开启审核工单物料：false-不开启，true-开启，当enableSpareAuthori=true时生效
      enableFeeAuthori: false, //是否开启工单费用权限：false-不开启，true-开启
      enableSpareAuthori: false, //	是否开启工单物料权限：false-不开启，true-开启
      orderBalanceStrategy: 1, // 报单余额策略: 1-不限制/余额不足亦可下单，2-余额不足禁止下单
    },
  })
  const isStop = (id) => {
    let arr: any = []
    arr = data.value.moduleSettlements.map((o) => {
      return o.moduleId
    })
    return arr.includes(id)
  }
  const rules = reactive({
    accountPhone: [
      { required: true, message: '请输入绑定的手机号', trigger: 'blur' },
      { validator: phone(data.value.phone), trigger: 'blur' },
    ],
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: phone(data.value.phone), trigger: 'blur' },
    ],
    name: [
      { required: true, message: '请输入商家名称', trigger: 'blur' },
      { max: 20, message: '长度不超过20个字符', trigger: 'blur' },
    ],
    username: [
      { required: true, message: '请输入联系人名称', trigger: 'blur' },
      { max: 20, message: '长度不超过20个字符', trigger: 'blur' },
    ],
    accountName: [{ required: true, message: '请输入负责人名称', trigger: ['change', 'blur'] }],
    province: [{ validator: setProvince(data.value.province), trigger: 'change' }],
    address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  })
  const empPageSelecctList = _.debounce((val) => {
    if (!verifyPhone(val)) {
      ElMessage({
        showClose: true,
        message: '请输入绑定账号获取',
        type: 'warning',
      })
      return
    }
    // 获取负责人信息
    getInfoAccount(val).then((res) => {
      if (res.data.success) {
        if (res.data.data.id.length > 0) {
          data.value.accountId = res.data.data.id
          data.value.accountName = res.data.data.name
          data.value.accountPhone = res.data.data.phone
          ElMessage({
            showClose: true,
            message: '获取成功',
            type: 'success',
          })
        } else {
          data.value.accountName = ''
          data.value.accountId = null
          isInput.value = false
          ElMessage({
            showClose: true,
            message: '获取不到，请手动输入！',
            type: 'warning',
          })
        }
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
        })
      }
    })
  }, 500)
  // 工单模块带费用下拉列表查询
  const inputWorkModC: any = ref({ val: '', index: null })
  const inputWorkModChange = (val, index) => {
    inputWorkModC.value.val = val
    inputWorkModC.value.index = index
  }
  watch(
    () => inputWorkModC.value.val,
    (n) => {
      workModulePricePageSelectList(n, inputWorkModC.value.index)
    },
  )
  const workModulePricePageSelectList = async (val, index = 0) => {
    loading.value = true
    let tem = {
      limit: 0,
      name: val,
      page: 0,
    }
    data.value.moduleSettlements[index] = {
      ...data.value.moduleSettlements[index],
      workModulePrice: [],
    }
    await workModulePricePageSelect(tem).then((res) => {
      if (data.value.moduleSettlements[index].workModulePrice) {
        data.value.moduleSettlements[index].workModulePrice = res.data.data.rows
      }
    })
    loading.value = false
  }
  // 新增模块费用
  const onAddItem = async () => {
    data.value.moduleSettlements.push({
      id: null,
      moduleId: null, //	模块ID
      price: null, //结算价
      containSpare: false, //是否包含物料：false-不包含，true-包含
      workModulePrice: [], //模块列表
    })
    await workModulePricePageSelectList('', data.value.moduleSettlements.length - 1)
  }
  // 删除模块费用
  const detelePri = (row, index) => {
    data.value.moduleSettlements = data.value.moduleSettlements.filter((o, index1) => {
      return index1 != index
    })
    if (row.id) {
      data.value.delModuleSettlementIds.push(row.id)
    }
  }
  // 批量填写
  const Allprice = ref()
  const changeAllAllprice = () => {
    if (data.value.moduleSettlements.length == 0) return
    data.value.moduleSettlements = data.value.moduleSettlements.map((o) => {
      return { ...o, price: Allprice.value }
    })
    popover2.value.hide()
  }
  // 批量填写
  const AllType = ref(false)
  const changeAllType = () => {
    if (data.value.moduleSettlements.length == 0) return
    data.value.moduleSettlements = data.value.moduleSettlements.map((o) => {
      return { ...o, containSpare: AllType.value }
    })
    AllType.value = false
    popover.value.hide()
  }
  // 保存
  async function addSave(formEl) {
    if (!formEl) return
    await formEl.validate(async (valid) => {
      if (valid) {
        let dataSave = _.cloneDeep(data.value)
        loadingSave.value = true
        await factorySave(dataSave).then((res) => {
          if (res.data.success) {
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'success',
            })
            router.push('/merchant/list')
            // refresh()
            TagsViewStore.delView(router.currentRoute.value.path)
          } else {
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
            })
          }
          loadingSave.value = false
        })
      }
    })
  }
  // 所属地址
  function addressValChange() {
    const addr = addrsDom.value.getSelectAddr()
    data.value.province = addr.province
    data.value.city = addr.city
    data.value.area = addr.area
    data.value.town = addr.town
  }
  // 获取新增后的详情
  async function getBeforeNetworkEditSelectData(id) {
    loadingSave.value = true
    if (route.params.id) {
      await getBeforeUpdateSelect(id).then((res) => {
        if (res.data.success) {
          let row = res.data.data.row
          data.value = { ...row }
          data.value.delModuleSettlementIds = [] //删除的服务模块结算对象ID
          if (row.moduleSettlements.length == 0) {
            onAddItem()
          } else {
            row.moduleSettlements.map((o, index) => {
              workModulePricePageSelectList('', index)
            })
          }
          addrs.value = {
            // 地址
            province: row.province,
            city: row.city,
            area: row.area,
            town: row.town,
          }
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
          })
        }
      })
    }
    loadingSave.value = false
  }

  // 取消
  const onBack = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
    router.back()
  }
  onMounted(async () => {
    if (route.params.id) {
      await getBeforeNetworkEditSelectData(route.params.id)
    } else {
      onAddItem()
    }
  })

  // 按钮取消聚焦
  const btnCancelFocus = (e: Event) => {
    ;(e.target as HTMLButtonElement).blur()
  }
</script>

<style scoped lang="scss">
  @import './index';
</style>
